<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 输入框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容"
                    clearable
                    @clear="getUserList"
                    v-model="queryInfo.query">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 按钮 -->
        <el-col :span="4">
          <el-button type="primary"
                     @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table :data="userList"
                stripe
                border>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名"
                         prop="username"></el-table-column>
        <el-table-column label="邮箱"
                         prop="email"></el-table-column>
        <el-table-column label="电话"
                         prop="mobile"></el-table-column>
        <el-table-column label="角色"
                         prop="roleName"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mgState"
                       @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="editUser(scope.row)"></el-button>
            <!-- 删除 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="deleteUser(scope.row.id)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark"
                        content="分配角色"
                        placement="top">
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 5, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addFormClose">
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户"
               :visible.sync="editDialogVisible"
               width="50%">
      <!-- 表格部分 -->
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="editForm.username"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱的验证规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 自定义手机号的验证规则
    var checkMobile = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regPhone = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/
      if (regPhone.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的电话号码'))
    }
    return {
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条
        pagesize: 2,
      },
      userList: [],
      total: 0,
      // 添加用户对话框
      addDialogVisible: false,
      // 添加用户的模型
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //用户信息规则
      addFormRules: {
        username: [
          {
            required: true, message: '请输入用户名', trigger: 'blur'
          },
          {
            min: 3, max: 10, message: '用户名的长度在3到10个字符之间', trigger: 'blur'
          }
        ],
        password: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            min: 6, max: 15, message: '密码的长度在6到15个字符之间', trigger: 'blur'
          }
        ],
        email: [
          {
            required: true, message: '请输入邮箱', trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请输入电话', trigger: 'blur'
          },
          {
            validator: checkMobile, trigger: 'blur'
          }
        ]
      },
      // 修改用户对话框
      editDialogVisible: false,
      //修改用户相关数据
      editForm: {
        username: '',
        id: '',
        email: '',
        mobile: ''
      },
      //修改用户相关规则
      editFormRules: {
        email: [
          {
            required: true, message: '请输入邮箱', trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请输入电话', trigger: 'blur'
          },
          {
            validator: checkMobile, trigger: 'blur'
          }
        ]
      }
    };
  },
  created () {
    this.getUserList();
  },
  methods: {
    // 得到用户数据
    getUserList () {
      this.$http.get("users", { params: this.queryInfo }).then((response) => {
        const res = response.data;
        console.log(res);
        if (res.code != 200) return this.$message.error("获取用户列表信息失败");
        this.userList = res.data.users;
        this.total = res.data.total;
      });
    },
    // 页面数据大小时间改变
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 当前页改变
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 用户状态改变
    userStateChanged (userInfo) {
      var qs = require('qs')
      this.$http.put("userstate", qs.stringify({ 'userId': userInfo.id }, { 'type': userInfo.mgState })).then((response) => {
        const res = response.data;
        if (res.code != 200) {
          userInfo.mgState = !userInfo.mgState
          return this.$message.error("用户状态切换出错")
        }
        this.$message.success("用户状态切换成功")
      });
    },
    // 添加用户对话框关闭时
    addFormClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 校验用户信息及登录
    addUser () {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        var qs = require('qs')
        this.$http.post('user', qs.stringify(this.addForm))
          .then((response) => {
            const res = response.data;
            if (res.code != 201) return this.$message.error(res.msg)
            else {
              this.addDialogVisible = false;
              this.getUserList();
              return this.$message.success(res.msg)
            }
          })
      })
    },
    // 查询数据库，得到该id对应的信息
    editUser (userInfo) {
      // console.log("====")
      // console.log(userInfo)
      this.editDialogVisible = true
      this.editForm.username = userInfo.username
      this.editForm.id = userInfo.id
      this.editForm.email = userInfo.email
      this.editForm.mobile = userInfo.mobile
    },
    // 修改用户 
    updateUser () {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        var qs = require('qs')
        this.$http.put('user', qs.stringify(this.editForm))
          .then((response) => {
            const res = response.data;
            if (res.code != 200) return this.$message.error(res.msg)
            else {
              this.editDialogVisible = false;
              this.getUserList();
              return this.$message.success(res.msg)
            }
          })
      })
    },
    // 删除用户
    async deleteUser (id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 取消对应字符串cancel 确认对应字符串confirm
      console.log(confirmResult)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      this.$http.delete("user", { params: { 'id': id } }).then((response) => {
        const res = response.data;
        if (res.code != 200) return this.$message.error(res.msg)
        else {
          this.getUserList();
          return this.$message.success(res.msg)
        }
      })


    }
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 12px;
  margin-bottom: 20px;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
}

.el-table {
  font-size: 12px;
  margin-top: 20px;
}
</style>